package com.yan_jiu_sheng.LeetCodeHot100.AC;

import java.util.HashMap;

/**
 * https://leetcode.cn/problems/copy-list-with-random-pointer/description/?envType=study-plan-v2&envId=top-100-liked
 * 通过
 *
 * @author yulongTian
 * @create 2024-05-31 13:30
 */
public class Test32 {
    public static void main(String[] args) {

    }

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        HashMap<Node, Integer> hashMap1 = new HashMap<>();
        HashMap<Integer, Node> hashMap2 = new HashMap<>();
        hashMap1.put(head, head.hashCode());
        Node resHead = new Node(head.val);
        hashMap2.put(head.hashCode(), resHead);
        Node p1 = head.next;
        Node p2 = resHead;
        while (p1 != null) {
            Node newNode = new Node(p1.val);
            hashMap1.put(p1, p1.hashCode());
            hashMap2.put(p1.hashCode(), newNode);
            p2.next = newNode;
            p2 = newNode;
            p1 = p1.next;
        }
        p1 = head;
        p2 = resHead;
        while (p1 != null) {
            if (p1.random != null) {
                Node random = p1.random;
                Integer integer = hashMap1.get(random);
                Node node = hashMap2.get(integer);
                p2.random = node;
            }
            p1 = p1.next;
            p2 = p2.next;
        }

        return resHead;
    }

}
